#pragma once
#include <mad.h>
#include "../base/file_io.h"

#define OUTPUT_BUFFER_SIZE	2048	// Must be an integer multiple of 4.
#define MAX_SOFT_MIX_PER_CH	8

class KMp3Decoder
{
public:
	KMp3Decoder();
	virtual ~KMp3Decoder();

	// Open the mp3 file, the total data in the mp3 file will be loaded into memory at once.
	bool OpenFile(const char* fileName);

	// Reset the decoder so that it will re-start from the beginning.
	void Reset();

	// Return if the stream reaches the end
	bool IsEOF() const;

	// This function will decode the mp3 file for the specified sampling count and mix the sound effect with
	// the destination buffer. NOTE: this function assumes the target buffer is in stereo mode, 
	// each sample have left & right sub-samples.
	unsigned int MixWithStreamBuffer(short* pDest, unsigned int sampleCnt);

private:
	static signed short MadFixedToSshort(mad_fixed_t Fixed);

private:
	KFileReader* mStreamPtr;
	void* mpStreamData;
	unsigned int mStreamSize;

	/************************************************************************
	libmad lowlevel stuff
	************************************************************************/
	// The following variables contain the music data, ie they don't change value until you load a new file
	mad_stream mStream;
	mad_frame mFrame;
	mad_synth mSynth;
	mad_timer_t mTimer;
	// The following varaibles hold the temporary buffer for the decoded audio stream.
	long mSamplesInOutput;
	signed short mOutputBuffer[OUTPUT_BUFFER_SIZE * 2];
	unsigned char *mOutputPtr;
	unsigned char *mGuardPtr;

	// The following variables will hold current playing status
	int mStatus;
	unsigned long mCurrentFrameIndex;

	// The following variables are maintained and updated by the tracker during playback
	volatile bool mIsPlaying;
	int mIsEOS;
};